package com.mz.mattress.admin.interceptor;

import com.mz.mattress.admin.common.FailMessage;
import com.mz.mattress.admin.common.Holder;
import com.mz.mattress.api.common.Constants;
import com.mz.mattress.api.redis.RedisKeys;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.common.ServiceException;
import com.mz.mattress.api.enums.FailCodeEnum;
import com.mz.mattress.api.jwt.JwtTokenUtil;
import com.mz.mattress.api.jwt.MerchantJwt;
import com.mz.mattress.api.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 商户和销售员 登陆拦截器
 */
@Slf4j
@Component
public class MerchantLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String HAS_LOCKED = JacksonUtils.toJson(Result.fail(FailMessage.MERCHANT_LOCKED));

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        String token = request.getHeader(Constants.LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            throw new ServiceException(FailCodeEnum.ACCOUNT_NOT_LOGIN);
        }

        MerchantJwt merchantJwt = JwtTokenUtil.parseMerchantToken(token);
        if (merchantJwt == null) {
            throw new ServiceException(FailCodeEnum.ACCOUNT_NOT_LOGIN);
        }

        String json = JacksonUtils.toJson(merchantJwt);
        log.info("token_merchant_json={}", json);

        log.info("token_merchant,memberMerId={},mobile={},type={},typeId={}",
                merchantJwt.getMemberMerId(), merchantJwt.getMobile(), merchantJwt.getType(), merchantJwt.getTypeId());

        if (merchantJwt.getType() == 1) {
            log.info("merchantId=" + merchantJwt.getTypeId());
            String merchantKey = RedisKeys.getLockMerchantKey(merchantJwt.getTypeId());
            Object obj = redisTemplate.opsForValue().get(merchantKey);
            if (obj != null) {
                log.info("merchantKey={},has_locked", merchantKey);
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType(Constants.CONTENT_TYPE);
                PrintWriter printWriter = response.getWriter();
                printWriter.write(HAS_LOCKED);
                return false;
            }
        }

        // 放入值
        Holder.MERCHANT_JWT_THREAD_LOCAL.set(merchantJwt);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //移除值
        Holder.ADMIN_JWT_THREAD_LOCAL.remove();
    }

}
